import axios from 'axios'
import { store } from '../store'
import { message } from 'ant-design-vue'

/**
 * 创建请求实例
 */
const instance = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 30000
})

/**
 * 为不同的请求类型设置默认的Content-Type
 */
instance.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
instance.defaults.headers.put['Content-Type'] = 'application/json;charset=UTF-8'
instance.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

/**
 * 请求拦截器
 */
instance.interceptors.request.use(
    (config) => {
        if (store.state.token !== '') {
            config.headers['Authorization'] = store.state.token
        }
        return config
    },
    (err) => {
        message.error(err.message)
    }
)

/**
 * 响应拦截器
 */
instance.interceptors.response.use(
    (res) => {
        return res
    },
    (err) => {
        if (err.response) {
            generateErrorHandler(err.response.status)
        } else {
            message.error(err.message)
        }
    }
)

/**
 * 错误码处理
 */
const generateErrorHandler = (code) => {
    switch (code) {
        case 400:
            message.error('请求语法错误，请检查代码及参数')
            break
        case 401:
            console.log('重新登陆')
            break
        case 403:
            message.warning('未授权的操作')
            break
        case 404:
            message.warning('您所请求的资源无法找到')
            break
        case 500:
            message.error('服务器内部错误，无法完成请求')
            break
        default:
            message.warning('服务暂不可用，请稍后再试')
    }
}

const request = {
    get: (url, params, options) => {
        return instance({
            url: url,
            method: 'GET',
            params: params,
            ...options
        })
    },
    post: (url, params, options) => {
        return instance({
            url: url,
            method: 'POST',
            data: JSON.stringify(params),
            ...options
        })
    },
    put: (url, params, options) => {
        return instance({
            url: url,
            method: 'PUT',
            data: JSON.stringify(params),
            ...options
        })
    },
    delete: (url, params, options) => {
        return instance({
            url: url,
            method: 'DELETE',
            params: params,
            ...options
        })
    },
    uploader: (url, params, options) => {
        return instance({
            url: url,
            method: 'POST',
            data: params,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            ...options
        })
    }
}

export default request
